﻿using System;
using System.Collections.Generic;
using System.Linq;
using Core.DAL;
using Core.Utils;

namespace Core.BOL
{
    public class StatViewsRepository : IDisposable
    {
        private ScoutNetDataContext context = null;

        #region Construtor
        public StatViewsRepository()
        {
            context = GeneralUtils.GetDataContext();
        }
        #endregion

        #region Methodes
        public void AddView(Guid mailID, Guid userID)
        {
            tMail_Stats_List mailStat = context.tMail_Stats_Lists.SingleOrDefault(p => p.ID == mailID);

            if (mailStat != null)
            {
                tMail_Stats_Count tStatCount = context.tMail_Stats_Counts.SingleOrDefault(p => p.MID == mailID && p.ID == userID);

                int numView = (tStatCount != null) ? tStatCount.NumView + 1 : 1;

                if (tStatCount != null)
                {
                    tStatCount.NumView = tStatCount.NumView + 1;
                }
                else
                {
                    tMail_Stats_Count mStatsCount = new tMail_Stats_Count()
                    {
                        ID = userID,
                        NumView = numView,
                        MID = mailID
                    };
                    context.tMail_Stats_Counts.InsertOnSubmit(mStatsCount);
                }
            }
        }

        public void DeleteViews(Guid mailID)
        {
            List<tMail_Stats_Count> tStatCount = context.tMail_Stats_Counts.Where(p => p.MID == mailID).ToList();
            if (tStatCount != null && tStatCount.Count > 0)
            {
                context.tMail_Stats_Counts.DeleteAllOnSubmit(tStatCount);
            }
        }

        public void DeleteUserViews(Guid UID)
        {
            List<tMail_Stats_Count> tStatCount = context.tMail_Stats_Counts.Where(p => p.ID == UID).ToList();
            if (tStatCount != null && tStatCount.Count > 0)
            {
                context.tMail_Stats_Counts.DeleteAllOnSubmit(tStatCount);
            }
        }

        public void Save()
        {
            context.SubmitChanges();
        }

        public void Dispose()
        {
            context.Dispose();
        }
        #endregion
    }
}
